<template>
    <div class="app-container">
        <el-form :inline="true" ref="queryForm">
            <el-form-item label="请假类型">
                <el-select v-model="queryParams.type" placeholder="请选择请假类型" clearable size="small">
                    <el-option
                            v-for="dict in typeOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="主题">
                <el-input
                        v-model="queryParams.title"
                        placeholder="请输入主题信息"
                        clearable
                        size="small"
                />
            </el-form-item>
            <el-form-item label="申请人姓名">
                <el-input
                        v-model="queryParams.applyName"
                        placeholder="请输入申请人姓名"
                        clearable
                        size="small"
                />
            </el-form-item>
            <el-form-item label="申请时间">
                <el-date-picker
                        v-model="dateRange"
                        size="small"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">查询</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type="success" icon="el-icon-plus" size="mini" v-hasPermi="['hr:leave:addLeave']" @click="handleAdd">新增请假条
                </el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" border :data="leaveList">
            <el-table-column label="序号" type="index" width="60"/>
            <el-table-column label="主题" prop="title" :show-overflow-tooltip="true"/>
            <el-table-column label="假单类型" align="center" prop="type" width="100"/>
            <el-table-column label="申请人" align="center" prop="applyName" />
            <el-table-column label="申请时间" align="center" prop="applyTime" width="160">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.applyTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态"  align="center" prop="status" />
            <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['hr:leave:modifyLeave']"
                            v-if="scope.row.status=='未提交'"
                    >修改草稿
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-circle-check"
                            v-if="scope.row.status=='未提交'"
                            v-hasPermi="['hr:leave:applyLeave']"
                            @click="applyLeave(scope.row)"
                    >提交申请
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            v-if="scope.row.status!='未提交'"
                            @click="handleView(scope.row)"
                    >假单详情
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-document"
                            v-if="scope.row.status!='未提交'"
                            @click="handleHistoryList(scope.row)"
                    >审批历史
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-picture-outline"
                            v-if="scope.row.status!='未提交'"
                            @click="handleHistoryImg(scope.row)"
                    >进度查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />
        <!-- 修改添加请假单信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" :show-close="false" width="650px" append-to-body>
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="主题信息" prop="title">
                            <el-input v-model="formData.title" placeholder="请输入请假主题信息" show-word-limit
                                      :style="{width: '100%'}"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="请假类型" prop="type">
                            <el-select v-model="formData.type" placeholder="请选择请假类型" clearable size="small">
                                <el-option
                                        v-for="dict in typeOptions"
                                        :key="dict.dictValue"
                                        :label="dict.dictLabel"
                                        :value="dict.dictValue"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="时间范围" prop="dateTimeRange">
                            <el-date-picker
                                    v-model="formData.dateTimeRange"
                                    type="datetimerange"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    @input="dateTimeChange"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="总时长" prop="totalTime">
                            <el-input v-model="formData.totalTimeStr" show-word-limit readonly :style="{width: '100%'}"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="请假原因" prop="reason">
                            <el-input v-model="formData.reason" type="textarea" placeholder="请输入请假原因"
                                      show-word-limit
                                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <template v-if="!viewFlag">
                    <el-button type="primary" v-hasPermi="['hr:leave:addAndApplyLeave']" @click="addAndApplyLeave">发起申请</el-button>
                    <el-button type="primary"  v-hasPermi="['hr:leave:addLeave']" @click="addLeave">保存为草稿</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </template>
                <el-button type="primary" v-if="viewFlag" @click="viewCancel">返回</el-button>
            </div>
        </el-dialog>
        <!--审批历史信息查看-->
        <ProcessListHistory
                :title="processHisTitle"
                :dialogFormVisible="processHisVisible"
                :historyList="processHistoryList"
                @cancel="processHisVisible = false">
        </ProcessListHistory>
        <ProcessImg
                :title="processImgTitle"
                :dialogFormVisible="processImgVisible"
                :imgUrl="processImgUrl"
                @cancel="processImgVisible = false">
        </ProcessImg>
    </div>
</template>

<script>
    import {addLeave,addAndApplyLeave,modifyLeave,applyLeave,listLeave} from "@/api/hr/leave.js";
    import {listHistory,showProcessImg} from "@/api/process/general.js";
    import ProcessListHistory from "@/views/components/process/processListHistory";
    import ProcessImg from "@/views/components/process/processImg";

    export default {
        name: "leaveList",
        components: {ProcessListHistory,ProcessImg},
        data() {
            return {
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    title: undefined,
                    type: undefined,
                    applyName: undefined
                },
                // 日期范围
                dateRange: [],
                // 请假类型数据字典
                typeOptions: [],
                // 公司数据
                leaveList: [],
                // 总条数
                total: 0,
                // 遮罩层
                loading: true,
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 表单参数
                formData: {
                    leaveId: undefined,
                    title: undefined,
                    type: undefined,
                    leaveStartTime: undefined,
                    leaveEndTime: undefined,
                    totalTime: undefined,
                    totalTimeStr: undefined,
                    dateTimeRange: undefined,
                    reason: undefined
                },
                // 表单校验
                rules: {
                    title: [{
                        required: true,
                        message: '请假主题信息不能为空',
                        trigger: 'blur'
                    }],
                    type: [{
                        required: true,
                        message: '请假类型不能为空',
                        trigger: 'change'
                    }],
                    dateTimeRange: [{
                        required: true,
                        message: '时间范围不能为空',
                        trigger: 'blur'
                    }],
                    reason: [{
                        required: true,
                        message: '请假原因不能为空',
                        trigger: 'blur'
                    }]
                },
                viewFlag: false,
                processHisTitle: "",
                processHisVisible: false,
                processHistoryList: [],
                processImgTitle: "",
                processImgVisible: false,
                processImgUrl: ""
            };
        },
        created() {
            this.getList();
            this.getDicts("hr_leave_type").then(response => {
                this.typeOptions = response.data;
            });
        },
        methods: {
            /** 查询假单列表 */
            getList() {
                this.loading = true;
                listLeave(this.addDateRange(this.queryParams, this.dateRange)).then(
                    response => {
                        this.leaveList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }
                );
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.$refs['queryForm'].resetFields();
                this.getList();
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.open = true;
                this.title = "新增请假条";
            },
            /** 时间范围选定后的回调函数*/
            dateTimeChange(dateTimeRange){
                this.$set(this.formData, "dateTimeRange",dateTimeRange);
                //选定时间后，计算时间差，并将数据放入到表单对象中去
                if(dateTimeRange != null && dateTimeRange.length>0){
                    this.formData.leaveStartTime = dateTimeRange[0];
                    this.formData.leaveEndTime = dateTimeRange[1];
                    this.formData.totalTime = this.stringToDate(dateTimeRange[1]) -  this.stringToDate(dateTimeRange[0]);
                    this.formData.totalTimeStr = this.getDuration(this.formData.totalTime);
                }
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                //添加其他数据
                //将列表中的选中对象信息拷贝到修改界面的对象中去,assign方法很重要，防止取消之后影响分页表格数据
                this.formData = Object.assign({}, row);
                this.$set(this.formData, "dateTimeRange", [row.leaveStartTime,row.leaveEndTime]);
                //this.formData.dateTimeRange = [row.leaveStartTime,row.leaveEndTime];
                this.formData.totalTimeStr = this.getDuration(this.formData.totalTime);
                this.open = true;
                this.title = "修改请假信息";
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.formData = {
                    leaveId: undefined,
                    title: undefined,
                    type: undefined,
                    leaveStartTime: undefined,
                    leaveEndTime: undefined,
                    totalTime: undefined,
                    totalTimeStr: undefined,
                    dateTimeRange: undefined,
                    reason: undefined
                };
                this.$refs['elForm'].resetFields();
            },
            /** 保存为草稿按钮 */
            addLeave: function () {
                this.$refs["elForm"].validate(valid => {
                    if (valid) {
                        //修改
                        if(this.formData.leaveId != undefined){
                            modifyLeave(this.formData).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("请假草稿修改成功！");
                                    this.getList();
                                    this.open = false;
                                } else {
                                    this.msgError(response.msg);
                                }
                            });
                        }else{
                            //添加
                            addLeave(this.formData).then(response => {
                                if (response.code === 200) {
                                    this.msgSuccess("请假草稿保存成功！");
                                    this.getList();
                                    this.open = false;
                                } else {
                                    this.msgError(response.msg);
                                }
                            });
                        }
                    }
                });
            },
            /** 添加并发起请假申请操作 */
            addAndApplyLeave() {
                let app = this;
                app.$refs["elForm"].validate(valid => {
                    if (valid) {
                        app.$confirm('确定发起请假申请吗？', "警告", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning"
                        }).then(function () {
                            addAndApplyLeave(app.formData).then(response => {
                                if (response.code === 200) {
                                    app.msgSuccess("请假单发起成功，请耐心等待领导审批！");
                                    app.getList();
                                    app.open = false;
                                } else {
                                    app.msgError(response.msg);
                                }
                            });
                        });
                    }
                });
            },
            applyLeave(row){
                let app = this;
                app.$confirm('确定发起请假申请吗？', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    applyLeave(row).then(response => {
                        if (response.code === 200) {
                            app.msgSuccess("请假单发起成功，请耐心等待领导审批！");
                            app.getList();
                            app.open = false;
                        } else {
                            app.msgError(response.msg);
                        }
                    });
                });
            },
            handleView(row){
                //添加其他数据
                //将列表中的选中对象信息拷贝到修改界面的对象中去,assign方法很重要，防止取消之后影响分页表格数据
                this.formData = Object.assign({}, row);
                this.$set(this.formData, "dateTimeRange", [row.leaveStartTime,row.leaveEndTime]);
                this.formData.totalTimeStr = this.getDuration(this.formData.totalTime);
                this.open = true;
                this.title = "查看请假详情";
                this.viewFlag = true;
            },
            handleHistoryList(row){
                var queryData = {instanceId: row.instanceId};
                listHistory(queryData).then(
                    response => {
                        this.processHistoryList = response.data;
                        this.processHisTitle = "查看审批历史信息";
                        this.processHisVisible = true;
                    }
                );
            },
            handleHistoryImg(row){
                this.processImgUrl = showProcessImg(row.instanceId);
                this.processImgTitle = "查看审批进度";
                this.processImgVisible = true;
            },
            viewCancel(){
                this.cancel();
                this.viewFlag = false;
            }
        }
    };
</script>
